<script setup lang="ts">
import { reactive, ref } from 'vue'
import { exportExcel, importExcel } from '@/utils/excel'
import { getTables, deleteTable, insertTables } from '@/api/examples'
import SytTable from '@/components/SytTable/SytTable.vue'
import SelectBox from '@/components/SelectBox/index.vue'
import { ElButton, ElMessage } from 'element-plus'
import TreeTable from '@/components/TreeTable/index.vue'
import TreeTableColumn from '@/components/TreeTable/TreeTableColumn.vue'
import ColumnSetting from '@/components/TableTools/ColumnSetting.vue'
import { getSummaries, getFilters, filterHandler } from '@/components/TableTools/utils'

let tableThs = ref([
  { title: '名字', dataIndex: 'name' },
  {
    title: 'a',
    children: [
      { title: 'b', dataIndex: 'b', sortable: true, showOverflowTooltip: true },
      { title: 'c', dataIndex: 'c' }
    ]
  }
])

let data = ref([])
let loading = ref(true)
let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)
const searchValue = ref('')

const initData = async () => {
  const query: any = {
    currentPage: currentPage.value,
    pageSize: pageSize.value
  }

  if (searchValue.value) query.name = searchValue.value

  await getTables(query).then((res) => {
    data.value = res.data.data
    total.value = res.data.total

    loading.value = false
  })
}

initData()

const handleDelete = (row) => {
  if (row.id) {
    deleteTable({ id: row.id }).then((res) => {
      initData()
    })
  } else ElMessage({ type: 'error', message: '不存在的id' })
}
// 多选数据
const handleSelectionChange = (val) => {
  console.log(val)
}
// 分页
const handlePaginationChange = (currentP, pSize) => {
  currentPage.value = currentP
  pageSize.value = pSize

  initData()
}

const insertMany = () => {
  insertTables([
    { name: '一', b: '1', c: '2' },
    { name: '二', b: '1', c: '2' }
  ]).then((res) => {
    if (res.code === 200) {
      initData()
    }
  })
}

// 导入excel
const handleImportExcel = async (fileObj) => {
  let jsonData = await importExcel(fileObj.raw)
  tableThs.value = Object.keys(jsonData[0]).map((v) => ({ title: v, dataIndex: v }))
  data.value = jsonData
}
// 导出excel
const handleExportExcel = async () => {
  await getTables().then((res) => {
    if (res.code == 200) exportExcel(tableThs.value, res.data.data)
  })
}
// 弹框选择
const searchBoxValue = ref(['eb3b0fcf-7953-4c56-9332-48b9fbaed917'])
const cacheData = ref([
  {
    id: 'eb3b0fcf-7953-4c56-9332-48b9fbaed917',
    name: '二'
  }
])
const selectProps = reactive({
  value: 'id',
  label: 'name',
  rows: 'data',
  total: 'total',
  currentPage: 'currentPage'
})
const headerData = reactive([
  {
    label: '名字',
    prop: 'name',
    queryable: true
  },
  {
    label: 'c',
    prop: 'c'
  },
  {
    label: 'c',
    prop: 'c',
    queryable: true,
    hidden: true,
    type: 'select',
    data: [
      { id: 1, name: '1' },
      { id: 2, name: '2' }
    ],
    valueKey: 'id',
    props: { value: 'id', label: 'name', children: 'children' }
  }
])
const dataMethod = async (query) => {
  return getTables(query).then((res) => res.data)
}
// 树表格
const treeData = ref([
  {
    cId: 2,
    cPid: 1,
    name: 'aa',
    cName: '2'
  },
  {
    cId: 2,
    cPid: 1,
    name: 'bb',
    cName: '2'
  },
  {
    cId: 4,
    cPid: 3,
    name: 'ee',
    cName: '4'
  },
  {
    cId: 5,
    cPid: 3,
    name: 'dd',
    cName: '5'
  }
])
const spanData = reactive({
  id: 'cId',
  pid: 'cPid',
  reference: [
    {
      cId: 1,
      cPid: 0,
      cName: '1'
    },
    {
      cId: 2,
      cPid: 1,
      cName: '2'
    },
    {
      cId: 3,
      cPid: 1,
      cName: '3'
    },
    {
      cId: 4,
      cPid: 3,
      cName: '4'
    },
    {
      cId: 5,
      cPid: 3,
      cName: '5'
    }
  ]
})
// 表格工具
/**
 *
 * 增减列需修改columnOptions
 * type字段类型
 * options下拉搜索内容
 * show: true展示列
 * width列宽
 * fixed固定左右 不能传空字符串''
 * total：true合计
 */
const columnOptions = ref([
  { label: '名称', value: 'name', type: 'string', width: '', fixed: 'left', show: true },
  { label: 'b', value: 'b', type: 'string', width: 120, fixed: false, show: true },
  { label: 'c', value: 'c', type: 'number', width: 120, fixed: false, show: true, total: true }
])
</script>

<template>
  <div v-loading="loading" element-loading-text="加载中...">
    <div class="tools">
      <span>{{ searchBoxValue }}</span>
      <SelectBox
        v-model="searchBoxValue"
        style="margin-right: 10px"
        :multiple="true"
        :props="selectProps"
        :header-data="headerData"
        :data-method="dataMethod"
        :cache-data="cacheData"
      >
        <ElButton>选择</ElButton>
      </SelectBox>
      <el-input
        v-model="searchValue"
        placeholder="输入name查询"
        class="searchValue"
        clearable
        @blur="initData"
      />
      <el-upload :auto-upload="false" :limit="1" :on-change="handleImportExcel">
        <el-button>导入excel</el-button>
      </el-upload>
      <el-button @click="handleExportExcel">导出excel</el-button>
      <el-button @click="insertMany()">insertMany</el-button>
    </div>

    <SytTable
      :columns="tableThs"
      :data="data"
      selection
      :pagination="{ total: total }"
      @selection-change="handleSelectionChange"
      @pagination-change="handlePaginationChange"
    >
      <template #operations="scope">
        <el-button size="small" type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
      </template>
    </SytTable>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 40, 50, 100]"
      class="pagination"
      @change="handlePaginationChange"
    />

    <TreeTable style="width: 100%" :data="treeData">
      <TreeTableColumn
        label="分类"
        prop="cName"
        :span-data="spanData"
        width="100px"
      ></TreeTableColumn>
      <TreeTableColumn label="名称" prop="name"></TreeTableColumn>
      <TreeTableColumn label="操作">
        <template #default="scope">
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
      </TreeTableColumn>
    </TreeTable>

    <ColumnSetting :options="columnOptions"></ColumnSetting>
    <el-table
      :data="data"
      :show-summary="columnOptions.some((item) => item.total)"
      :summary-method="(data) => getSummaries(data, columnOptions)"
      border
      stripe
      tooltip-effect="dark"
    >
      <el-table-column label="序号" type="index" width="90" align="center" fixed="left" />

      <template v-for="item of columnOptions" :key="item.value">
        <el-table-column
          v-if="item.show"
          :label="item.label"
          align="center"
          :prop="item.value"
          :width="item.width"
          :fixed="item.fixed"
          :filters="getFilters(item.value, data)"
          :filter-method="filterHandler"
          show-overflow-tooltip
        >
          <template #filter-icon>
            <el-icon>
              <Filter />
            </el-icon>
          </template>

          <template v-if="item.value == 'mc'" #default="scope">
            <el-link underline="never" type="primary">
              {{ scope.row.mc }}
            </el-link>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<style scoped>
:deep(.el-upload) {
  margin-right: 12px;
}

.tools {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.searchValue {
  width: 150px;
  height: 35px;
  margin-right: 10px;
}

.pagination {
  margin-top: 10px;
}
</style>
